package homegroup.inc.servlets;

import homegroup.inc.dao.BookDAO;
import homegroup.inc.dto.Book;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.fileupload.*;
/**
 * Created by stardust on 30.10.2014.
 */
@WebServlet(urlPatterns = "/uploadbook")
@MultipartConfig
//        (
//        location="/tmp",
//        fileSizeThreshold=5*1024*1024,
//        maxFileSize=40*1024*1024,
//        maxRequestSize=50*1024*1024)
public class UploadBook extends HttpServlet {

    @EJB
    BookDAO bookDAO;

    private Book book;

    private final static Logger LOGGER =
            Logger.getLogger(UploadBook.class.getCanonicalName());

//    private static final String UPLOAD_DIRECTORY = "upload";
//    private static final int TRESHHOLD_SIZE = 1024 * 1024 * 3;
//    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
//    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;

    private boolean isMultipart;
    private String filePath;
    private int maxFileSize = 50 * 1024 * 1024;
    private int maxMemSize = 3 * 1024 * 1024;

    @Override
    public void init() throws ServletException {
        filePath = getServletContext().getInitParameter("file-upload");
        super.init();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Map<String, String[]> formParams = req.getParameterMap();


        book = new Book();
        book.setCoverPath(formParams.get("coverpath")[0]);
        book.setAuthor(formParams.get("author")[0]);
        book.setBookPath(formParams.get("bookpath")[0]);
        book.setISBN(formParams.get("isbn")[0]);
        book.setDescription(formParams.get("description")[0]);
        book.setPublisher(formParams.get("publisher")[0]);
        book.setTitle(formParams.get("title")[0]);

        bookDAO.create(book);
    }

    protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)  throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        //Create path components to save the file
        final String path = request.getParameter("destination");
        final Part filePart = request.getPart("file");
        final String fileName = getFileName(filePart);

    }

    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }


}
